#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    //设置窗口标题
    this->setWindowTitle("服务器");
    //tcp对象实例化
    socket = new QTcpServer(this);
    //绑定newConnection的信号槽函数
    connect(socket, &QTcpServer::newConnection, this, &Widget::processConnection);

    //进行bind和listen操作
    bool retlisten = socket->listen(QHostAddress::Any, 8082);
    if(retlisten == false)
    {
        QMessageBox::critical(this, "服务器启动失败", socket->errorString());
        return;
    }
}

Widget::~Widget()
{
    delete ui;
}

//获取新连接的信号处理函数
void Widget::processConnection()
{
    //获取新连接
    QTcpSocket* client = socket->nextPendingConnection();
    //构建日志
    QString log = "[" + client->peerAddress().toString() + ":" + QString::number(client->peerPort()) + "] 新客户端上线";
    ui->listWidget->addItem(log);

    //通过信号槽触发接收消息
    connect(client, &QTcpSocket::readyRead, this, [=](){
        //读取消息
        QString message = client->readAll();
        //处理消息--此处没有处理，只是回显
        //写回到客户端
        client->write(message.toUtf8());
        //构建日志
        QString log = "[" + client->peerAddress().toString() + ":" + QString::number(client->peerPort()) + "] say: " + message;
        //写到界面
        ui->listWidget->addItem(log);
    });

    //处理断开连接的信号槽函数
    connect(client, &QTcpSocket::disconnected, this, [=](){
        //构建日志
        QString log = "[" + client->peerAddress().toString() + ":" + QString::number(client->peerPort()) + "] 客户端下线";
        //释放对象
        client->deleteLater();
    });
}

